/**
 *
 * 2007-11-3 下午02:21:27
 * @author xuhuan
 */

package edu.ccut.saturn.studio.logic.model.commands;

import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;

import edu.ccut.saturn.studio.logic.model.ShapesDiagram;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnEndIterationNode;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnStartIterationNode;

public class CreateForCommand extends Command {

	private SaturnStartIterationNode saturnStartIterationNode;

	private SaturnEndIterationNode saturnEndIterationNode;

	private final ShapesDiagram parent;

	private Rectangle bounds;

	/**
	 * Create a command that will add a new Shape to a ShapesDiagram.
	 * 
	 * @param newShape
	 *            the new Shape that is to be added
	 * @param parent
	 *            the ShapesDiagram that will hold the new element
	 * @param bounds
	 *            the bounds of the new shape; the size can be (-1, -1) if not
	 *            known
	 * @throws IllegalArgumentException
	 *             if any parameter is null, or the request does not provide a
	 *             new Shape instance
	 */
	public CreateForCommand(SaturnStartIterationNode saturnStartIterationNode,
			SaturnEndIterationNode saturnEndIterationNode, ShapesDiagram parent,
			Rectangle bounds) {
		this.saturnStartIterationNode = saturnStartIterationNode;
		this.saturnEndIterationNode = saturnEndIterationNode;
		this.parent = parent;
		this.bounds = bounds;
		setLabel("shape creation");
	}

	/**
	 * Can execute if all the necessary information has been provided.
	 * 
	 * @see org.eclipse.gef.commands.Command#canExecute()
	 */
	public boolean canExecute() {
		return saturnStartIterationNode != null && saturnEndIterationNode != null
				&& parent != null && bounds != null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#execute()
	 */
	public void execute() {
		saturnStartIterationNode.setLocation(bounds.getLocation());
		saturnEndIterationNode.setLocation(new Point(
				bounds.getLocation().x + 50, bounds.getLocation().y + 50));
		Dimension size = bounds.getSize();
		if (size.width > 0 && size.height > 0) {
			saturnStartIterationNode.setSize(size);
			saturnEndIterationNode.setSize(size);
		}
		redo();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#redo()
	 */
	public void redo() {
		parent.addShape(saturnStartIterationNode);
		parent.addShape(saturnEndIterationNode);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#undo()
	 */
	public void undo() {
		parent.removeShape(saturnStartIterationNode);
		parent.removeShape(saturnEndIterationNode);
	}

}
